package Socket;

import java.io.*;
import java.net.Socket;

public class SockUtil {
    public static String receiveMsg(Socket socket) throws IOException {
        //服务器读取客户端传输的信息
        System.out.println("开始接收信息");
        InputStream is = socket.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader reader = new BufferedReader(isr);
//        StringBuilder builder = new StringBuilder();
        String line;
        //readLine读到\n或\r停止,不会将\n读进去
//        while ((line = reader.readLine()) != null){
//            builder.append(line);
//        }
        line = reader.readLine();

        System.out.println(line);
        //标识输入通道中的数据已经被读取完毕，如果再读取，则直接读取到-1。
        //表示读取结束
//        socket.shutdownInput();
        return line;
    }

    public static void sendMsg(Socket socket, String msg) throws IOException {
        //判断字符串末尾有没有\n,有就不加\n，没有就加
        //方便读入判断结尾
        //是\n结尾为true不是为false
        if(!msg.endsWith("\n")) {
            msg += "\n";
        }
        System.out.print("加了\\n的msg"+msg);
        //获取客户端输出的通道
        OutputStream os = socket.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os);
        BufferedWriter writer = new BufferedWriter(osw);
        writer.write(msg);
        writer.flush();
        //客户端输出已经完成，如果再向通道中写数据，那么将会报IOException
//        socket.shutdownOutput();
    }
}
